package cn.sofwin.web.blog.servlet;

import cn.sofwin.web.blog.entity.User;
import cn.sofwin.web.blog.service.UserService;
import cn.sofwin.web.blog.service.impl.UserServiceImpl;
import cn.sofwin.web.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blog/user/login")
public class LoginServlet extends HttpServlet {
    UserService userService= UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 转发到的类页面
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理注册请求
        HttpHelper.charset(req);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            HttpHelper.error("用户名或密码错误!", req, resp);
        }else{
            User user = userService.login(username, password);
            if(user == null){
                HttpHelper.error("用户名或密码错误!", req, resp);
            }else{
                //将登录成功的用户信息存到session
                req.getSession().setAttribute("LOGIN_USER",user);
                System.out.println(user);

                // 重定向到首页
                resp.sendRedirect("/index");
            }
        }
    }
}
